package com.wk.springboot.retry;

import com.wk.springboot.retry.config.RetryConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;

@Component
@Slf4j
public class ExponentialBackoffRetry implements RetryStrategy {
    @Autowired
    RetryConfiguration retryConfiguration;
    // 默认配置（可通过配置中心动态更新）


    private java.util.Random random = new java.util.Random();

    @Override
    public Date calculateNextRetryTime(int retryCount, Date lastRetryTime) {
        long baseInterval = (long) (retryConfiguration.getInitialInterval() * Math.pow(retryConfiguration.getMultiplie(), retryCount - 1));
        long interval = Math.min(baseInterval, retryConfiguration.getMaxInterval());
        
        // 添加随机抖动避免惊群效应
        long jitter = (long) (interval * retryConfiguration.getJitterFactor() * Math.random());
        interval = interval + (random.nextBoolean() ? jitter : -jitter);
        
        return new Date(System.currentTimeMillis() + interval);
    }

    @Override
    public boolean allowRetry(int retryCount) {
        return retryCount < retryConfiguration.getMaxInterval();
    }

}